package cn.edu.ctbu.finaltest.controller;

import cn.edu.ctbu.finaltest.core.PageUtils;
import cn.edu.ctbu.finaltest.core.RUtil;
import cn.edu.ctbu.finaltest.domain.*;
import cn.edu.ctbu.finaltest.exception.REnum;
import cn.edu.ctbu.finaltest.exception.RException;
import cn.edu.ctbu.finaltest.service.AdministratorSelectCourseService.AdministratorSelectCourseService;
import cn.edu.ctbu.finaltest.service.AdministratorService.AdministratorService;
import cn.edu.ctbu.finaltest.service.AdministratorTeacherTeachingService.AdministratorTeacherTeachingService;
import cn.edu.ctbu.finaltest.service.CourseService.CourseService;
import cn.edu.ctbu.finaltest.service.SelectCourseService.SelectCourseService;
import cn.edu.ctbu.finaltest.service.StudentCourseMessageService.StudentCourseMessageService;
import cn.edu.ctbu.finaltest.service.StudentSelectCourseService.StudentSelectCourseService;
import cn.edu.ctbu.finaltest.service.StudentService.StudentService;
import cn.edu.ctbu.finaltest.service.TeacherCourseService.TeacherCourseService;
import cn.edu.ctbu.finaltest.service.TeacherService.TeacherService;
import cn.edu.ctbu.finaltest.vo.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class AdministratorController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private SelectCourseService selectCourseService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private TeacherCourseService teacherCourseService;
    @Autowired
    private StudentCourseMessageService studentCourseMessageService;
    @Autowired
    private StudentSelectCourseService studentSelectCourseService;
    @Autowired
    private AdministratorService administratorService;
    @Autowired
    private AdministratorSelectCourseService administratorSelectCourseService;
    @Autowired
    private AdministratorTeacherTeachingService administratorTeacherTeachingService;

    @RequestMapping("/administrator/administratorListStudent.html")
    public String administratorListStudentDisplay(){return "administrator/administratorListStudent";}
    @RequestMapping("/administrator/administratorListTeacher.html")
    public String administratorListTeacherDisplay(){return "administrator/administratorListTeacher";}
    @RequestMapping("/administrator/administratorListCourse.html")
    public String administratorListCourseDisplay(){return "administrator/administratorListCourse";}
    @RequestMapping("/administrator/administratorListSelectCourse.html")
    public String administratorListSelectCourseDisplay(){return "administrator/administratorListSelectCourse";}
    @RequestMapping("/administrator/administratorListTeacherCourse.html")
    public String administratorListTeacherCourseDisplay(){return "administrator/administratorListTeacherCourse";}
    @RequestMapping("/administrator/loginScreen.html")
    public String administratorLoginScreen(){return "login/loginScreen";}

    @ResponseBody
    @RequestMapping("/administrator/showName")
    public String administratorName(HttpServletRequest httpServletRequest) throws Exception{
        HttpSession session = httpServletRequest.getSession();
        if (!session.getAttribute("choose").equals("3") || session.getAttribute("userid") == null){
            throw new RException(REnum.LOGIN_ERR);
        }
        Administrator administratorMessage = (Administrator) session.getAttribute("user");
        return administratorMessage.getAname();
    }

    @ResponseBody
    @RequestMapping("/administrator/displayListStudent")
    public R administratorGetByPageStudent(@RequestParam(value = "page",defaultValue = "0") Integer page,
                                           @RequestParam(value = "size",defaultValue = "10") Integer size,
                                           @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                                           HttpServletRequest httpServletRequest) throws Exception {
        HttpSession session = httpServletRequest.getSession();
        if (!session.getAttribute("choose").equals("3") || session.getAttribute("userid") == null) {
            throw new RException(REnum.LOGIN_ERR);
        }

        R<List<Student>> RStudents = studentService.findRAll();

        int RStudentsSize = RStudents.getData().size();
        RStudents.setData(RStudents.getData().stream().skip((pageNum - 1) * size).limit(size).collect(Collectors.toList()));
        PageUtils pageUtils = new PageUtils(RStudents.getData(), RStudentsSize);
        return RUtil.success(pageUtils);
    }

    @ResponseBody
    @RequestMapping("/administrator/searchStudent")
    public R administratorSearchStudent(@RequestParam(value = "size",defaultValue = "10") Integer size,
                                   @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                                   @RequestParam(value = "name",defaultValue = "") String name,
                                   HttpServletRequest httpServletRequest){
        HttpSession session = httpServletRequest.getSession();
        if (!session.getAttribute("choose").equals("3") || session.getAttribute("userid") == null){
            throw new RException(REnum.LOGIN_ERR);
        }

        String[] arrayList = name.split("!");

        name = arrayList[0];
        String searchOption = arrayList[1];
        String searchMatching = arrayList[2];


        R<List<Student>> studentMessageR = new R<>();
        List<Student> students = new ArrayList<>();

        if (searchMatching.equals("20")) {//模糊查询
            if (searchOption.equals("10")) {//学号
                studentMessageR.setData(studentService.findByRSnoLike(name).getData());
                studentMessageR.setCode(REnum.SUCCESS.getCode());
                studentMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else if (searchOption.equals("11")) {//姓名
                studentMessageR.setData(studentService.findByRNameLike(name).getData());
                studentMessageR.setCode(REnum.SUCCESS.getCode());
                studentMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else if (searchOption.equals("12")) {//性别
                studentMessageR.setData(studentService.findByRSexLike(name).getData());
                studentMessageR.setCode(REnum.SUCCESS.getCode());
                studentMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else  {//专业
                studentMessageR.setData(studentService.findByRDeptLike(name).getData());
                studentMessageR.setCode(REnum.SUCCESS.getCode());
                studentMessageR.setMsg(REnum.SUCCESS.getMsg());
            }
        } else {//精确查询
            if (searchOption.equals("10")) {//学号
                students.add(studentService.findByRSno(name).getData());
                if (students.get(0).getId() == null){
                    students = new ArrayList<>();
                }
                studentMessageR.setData(students);
                studentMessageR.setCode(REnum.SUCCESS.getCode());
                studentMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else if (searchOption.equals("11")) {//姓名
                studentMessageR.setData(studentService.findByRName(name).getData());
                studentMessageR.setCode(REnum.SUCCESS.getCode());
                studentMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else if (searchOption.equals("12")) {//性别
                studentMessageR.setData(studentService.findByRSex(name).getData());
                studentMessageR.setCode(REnum.SUCCESS.getCode());
                studentMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else  {//专业
                studentMessageR.setData(studentService.findByRDept(name).getData());
                studentMessageR.setCode(REnum.SUCCESS.getCode());
                studentMessageR.setMsg(REnum.SUCCESS.getMsg());
            }
        }

        int studentMessageRSize = studentMessageR.getData().size();
        studentMessageR.setData(studentMessageR.getData().stream().skip((pageNum - 1) * size).limit(size).collect(Collectors.toList()));
        PageUtils pageUtils = new PageUtils(studentMessageR.getData(), studentMessageRSize);
        return RUtil.success(pageUtils);
    }

    @ResponseBody
    @DeleteMapping("/administrator/deleteStudent/{sno}")
    public void delete(@PathVariable String sno){
        R<List<SelectCourse>> selectCourseR = selectCourseService.findByRSno(sno);
        for (int i = 0;i < selectCourseR.getData().size();i++){
            selectCourseService.deleteId(selectCourseR.getData().get(i).getId());
        }
        studentService.deleteId(studentService.findByRSno(sno).getData().getId());
    }

    @ResponseBody
    @GetMapping("/administrator/getStudent/{sno}")
    public Student getStudent(@PathVariable String sno){
        R<Student> studentR = studentService.findByRSno(sno);
        return studentR.getData();
    }

    @ResponseBody
    @PostMapping("administrator/insertStudent")
    public void insertStudent(Student student){
        if (studentService.findByRSno(student.getSno()).getData().getSno() != null){
            throw new RException(REnum.INSERTSTUDENT_ERR);
        }
        if (student.getSex().equals("1")){
            student.setSex("男");
        } else {
            student.setSex("女");
        }
        studentService.insert(student);
    }

    @ResponseBody
    @PutMapping("administrator/updateStudent")
    public void updateStudent(Student student){
        if (student.getSex().equals("1")){
            student.setSex("男");
        } else {
            student.setSex("女");
        }
        studentService.update(student);
    }

    @ResponseBody
    @RequestMapping("/administrator/displayListTeacher")
    public R administratorGetByPageTeacher(@RequestParam(value = "page",defaultValue = "0") Integer page,
                                                   @RequestParam(value = "size",defaultValue = "10") Integer size,
                                                   @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                                                   HttpServletRequest httpServletRequest) throws Exception {
        HttpSession session = httpServletRequest.getSession();
        if (!session.getAttribute("choose").equals("3") || session.getAttribute("userid") == null) {
            throw new RException(REnum.LOGIN_ERR);
        }

        R<List<Teacher>> RTeachers = teacherService.findRAll();

        int RTeacherSize = RTeachers.getData().size();
        RTeachers.setData(RTeachers.getData().stream().skip((pageNum - 1) * size).limit(size).collect(Collectors.toList()));
        PageUtils pageUtils = new PageUtils(RTeachers.getData(), RTeacherSize);
        return RUtil.success(pageUtils);
    }


    @ResponseBody
    @RequestMapping("/administrator/searchTeacher")
    public R administratorSearchTeacher(@RequestParam(value = "size",defaultValue = "10") Integer size,
                                                @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                                                @RequestParam(value = "name",defaultValue = "") String name,
                                                HttpServletRequest httpServletRequest){
        HttpSession session = httpServletRequest.getSession();
        if (!session.getAttribute("choose").equals("3") || session.getAttribute("userid") == null){
            throw new RException(REnum.LOGIN_ERR);
        }

        String[] arrayList = name.split("!");

        name = arrayList[0];
        String searchOption = arrayList[1];
        String searchMatching = arrayList[2];


        R<List<Teacher>> teacherMessageR = new R<>();
        List<Teacher> Teachers = new ArrayList<>();

        if (searchMatching.equals("20")) {//模糊查询
            if (searchOption.equals("10")) {//工号
                teacherMessageR.setData(teacherService.findByRTnoLike(name).getData());
                teacherMessageR.setCode(REnum.SUCCESS.getCode());
                teacherMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else if (searchOption.equals("11")) {//姓名
                teacherMessageR.setData(teacherService.findByRNameLike(name).getData());
                teacherMessageR.setCode(REnum.SUCCESS.getCode());
                teacherMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else if (searchOption.equals("12")) {//性别
                teacherMessageR.setData(teacherService.findByRSexLike(name).getData());
                teacherMessageR.setCode(REnum.SUCCESS.getCode());
                teacherMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else if (searchOption.equals("13")) {//年龄
                teacherMessageR.setData(teacherService.findByRAgeLike(Integer.parseInt(name)).getData());
                teacherMessageR.setCode(REnum.SUCCESS.getCode());
                teacherMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else if (searchOption.equals("14")) {//职称
                teacherMessageR.setData(teacherService.findByRProfLike(name).getData());
                teacherMessageR.setCode(REnum.SUCCESS.getCode());
                teacherMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else {//院系
                teacherMessageR.setData(teacherService.findByRDeptLike(name).getData());
                teacherMessageR.setCode(REnum.SUCCESS.getCode());
                teacherMessageR.setMsg(REnum.SUCCESS.getMsg());
            }
        } else {//精确查询
            if (searchOption.equals("10")) {//工号
                Teachers.add(teacherService.findByRTno(name).getData());
                if (Teachers.get(0).getId() == null){
                    Teachers = new ArrayList<>();
                }
                teacherMessageR.setData(Teachers);
                teacherMessageR.setCode(REnum.SUCCESS.getCode());
                teacherMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else if (searchOption.equals("11")) {//姓名
                teacherMessageR.setData(teacherService.findByRName(name).getData());
                teacherMessageR.setCode(REnum.SUCCESS.getCode());
                teacherMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else if (searchOption.equals("12")) {//性别
                teacherMessageR.setData(teacherService.findByRSex(name).getData());
                teacherMessageR.setCode(REnum.SUCCESS.getCode());
                teacherMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else if (searchOption.equals("13")) {//年龄
                teacherMessageR.setData(teacherService.findByRAge(Integer.parseInt(name)).getData());
                teacherMessageR.setCode(REnum.SUCCESS.getCode());
                teacherMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else if (searchOption.equals("14")) {//职称
                teacherMessageR.setData(teacherService.findByRProf(name).getData());
                teacherMessageR.setCode(REnum.SUCCESS.getCode());
                teacherMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else {//院系
                teacherMessageR.setData(teacherService.findByRDept(name).getData());
                teacherMessageR.setCode(REnum.SUCCESS.getCode());
                teacherMessageR.setMsg(REnum.SUCCESS.getMsg());
            }
        }

        int teacherMessageRSize = teacherMessageR.getData().size();
        teacherMessageR.setData(teacherMessageR.getData().stream().skip((pageNum - 1) * size).limit(size).collect(Collectors.toList()));
        PageUtils pageUtils = new PageUtils(teacherMessageR.getData(), teacherMessageRSize);
        return RUtil.success(pageUtils);
    }

    @ResponseBody
    @DeleteMapping("/administrator/deleteTeacher/{tno}")
    public void deleteTeacher(@PathVariable String tno){
        R<List<TeacherCourse>> teachercourseR = teacherCourseService.findByRTno(tno);
        for (int i = 0;i < teachercourseR.getData().size();i++){
            teacherService.deleteId(teachercourseR.getData().get(i).getId());
        }
        teacherService.deleteId(teacherService.findByRTno(tno).getData().getId());
    }

    @ResponseBody
    @GetMapping("/administrator/getTeacher/{tno}")
    public Teacher getTeacher(@PathVariable String tno){
        R<Teacher> TeacherR = teacherService.findByRTno(tno);
        return TeacherR.getData();
    }

    @ResponseBody
    @PostMapping("administrator/insertTeacher")
    public void insertTeacher(Teacher teacher){
        if (teacherService.findByRTno(teacher.getTno()).getData().getTno() != null){
            throw new RException(REnum.INSERTTEACHER_ERR);
        }
        System.out.println("test insert:"+teacher);
        if (teacher.getSex().equals("1")){
            teacher.setSex("男");
        } else {
            teacher.setSex("女");
        }
        teacherService.insert(teacher);
    }

    @ResponseBody
    @PutMapping("administrator/updateTeacher")
    public void updateTeacher(Teacher teacher){

        System.out.println("test update:"+teacher);
        if (teacher.getSex().equals("1")){
            teacher.setSex("男");
        } else {
            teacher.setSex("女");
        }
        teacherService.update(teacher);
    }

    @ResponseBody
    @RequestMapping("/administrator/displayListCourse")
    public R administratorGetByPageCourse(@RequestParam(value = "page",defaultValue = "0") Integer page,
                                                   @RequestParam(value = "size",defaultValue = "10") Integer size,
                                                   @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                                                   HttpServletRequest httpServletRequest) throws Exception {
        HttpSession session = httpServletRequest.getSession();
        if (!session.getAttribute("choose").equals("3") || session.getAttribute("userid") == null) {
            throw new RException(REnum.LOGIN_ERR);
        }

        R<List<Course>> RCourse = courseService.findRAll();

        int RCourseSize = RCourse.getData().size();
        RCourse.setData(RCourse.getData().stream().skip((pageNum - 1) * size).limit(size).collect(Collectors.toList()));
        PageUtils pageUtils = new PageUtils(RCourse.getData(),RCourseSize);
        return RUtil.success(pageUtils);
    }

    @ResponseBody
    @RequestMapping("/administrator/searchCourse")
    public R administratorSearchCourse(@RequestParam(value = "size",defaultValue = "10") Integer size,
                                                @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                                                @RequestParam(value = "name",defaultValue = "") String name,
                                                HttpServletRequest httpServletRequest){
        HttpSession session = httpServletRequest.getSession();
        if (!session.getAttribute("choose").equals("3") || session.getAttribute("userid") == null){
            throw new RException(REnum.LOGIN_ERR);
        }

        String[] arrayList = name.split("!");

        name = arrayList[0];
        String searchOption = arrayList[1];
        String searchMatching = arrayList[2];


        R<List<Course>> courseMessageR = new R<>();
        List<Course> courses = new ArrayList<>();

        if (searchMatching.equals("20")) {//模糊查询
            if (searchOption.equals("10")) {//课号
                courseMessageR.setData(courseService.findByRCnoLike(name).getData());
                courseMessageR.setCode(REnum.SUCCESS.getCode());
                courseMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else if (searchOption.equals("11")) {//课名
                courseMessageR.setData(courseService.findByRNameLike(name).getData());
                courseMessageR.setCode(REnum.SUCCESS.getCode());
                courseMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else if (searchOption.equals("12")) {//课时
                courseMessageR.setData(courseService.findByRHourLike(Integer.parseInt(name)).getData());
                courseMessageR.setCode(REnum.SUCCESS.getCode());
                courseMessageR.setMsg(REnum.SUCCESS.getMsg());
            }  else {//学分
                courseMessageR.setData(courseService.findByRCreditLike(Float.parseFloat(name)).getData());
                courseMessageR.setCode(REnum.SUCCESS.getCode());
                courseMessageR.setMsg(REnum.SUCCESS.getMsg());
            }
        } else {//精确查询
            if (searchOption.equals("10")) {//课号
                courses.add(courseService.findByRCno(name).getData());
                if (courses.get(0).getId() == null){
                    courses = new ArrayList<>();
                }
                courseMessageR.setData(courses);
                courseMessageR.setCode(REnum.SUCCESS.getCode());
                courseMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else if (searchOption.equals("11")) {//课名
                courseMessageR.setData(courseService.findByRName(name).getData());
                courseMessageR.setCode(REnum.SUCCESS.getCode());
                courseMessageR.setMsg(REnum.SUCCESS.getMsg());
            } else if (searchOption.equals("12")) {//课时
                courseMessageR.setData(courseService.findByRHour(Integer.parseInt(name)).getData());
                courseMessageR.setCode(REnum.SUCCESS.getCode());
                courseMessageR.setMsg(REnum.SUCCESS.getMsg());
            }  else {//学分
                courseMessageR.setData(courseService.findByRCredit(Float.parseFloat(name)).getData());
                courseMessageR.setCode(REnum.SUCCESS.getCode());
                courseMessageR.setMsg(REnum.SUCCESS.getMsg());
            }
        }

        int courseMessageRSize = courseMessageR.getData().size();
        courseMessageR.setData(courseMessageR.getData().stream().skip((pageNum - 1) * size).limit(size).collect(Collectors.toList()));
        PageUtils pageUtils = new PageUtils(courseMessageR.getData(), courseMessageRSize);
        return RUtil.success(pageUtils);
    }



    @ResponseBody
    @DeleteMapping("/administrator/deleteCourse/{cno}")
    public void deleteCourse(@PathVariable String cno){
        //删除选课表、授课表、课表内相应内容
        for (int i = 0;i < teacherCourseService.findByRCno(cno).getData().size();i++){
            teacherCourseService.deleteId(teacherCourseService.findByRCno(cno).getData().get(i).getId());
        }
        for (int i = 0;i < selectCourseService.findByRCno(cno).getData().size();i++){
            selectCourseService.deleteId(selectCourseService.findByRCno(cno).getData().get(i).getId());
        }
        courseService.deleteId(courseService.findByRCno(cno).getData().getId());
    }

    @ResponseBody
    @GetMapping("/administrator/getCourse/{cno}")
    public Course getCourse(@PathVariable String cno){
        R<Course> courseR = courseService.findByRCno(cno);
        return courseR.getData();
    }

    @ResponseBody
    @PostMapping("administrator/insertCourse")
    public void insertCourse(Course course) throws RException{
        if (courseService.findByRCno(course.getCno()).getData().getCno() != null){
            throw new RException(REnum.INSERTCOURSE_ERR);
        }
        courseService.insert(course);
    }

    @ResponseBody
    @PutMapping("administrator/updateCourse")
    public void updateCourse(Course course){

        courseService.update(course);
    }



}
